package com.juc.cyclicbarrier.cyclicbarrier5;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class MyService {

	/**
	 * 方法isBroken()查询此屏障是否处于损坏状态
	 */
	/**
	 * 类CyclicBarrier对线程的interrupt处理会使用全有或者全无的的破坏模型（breakage model）,
	 * 意思是如果有一个线程由于中断或者超时提前离开了屏障点，其他在屏障点等待的线程也会抛出
	 * BrokenBarrierException 或 者InterruptedException 异常，并离开屏障点
	 */
	private CyclicBarrier cbRef;
	
	public MyService(CyclicBarrier cbRef){
		super();
		this.cbRef = cbRef;
	}
	
	private void beginRun(int count) {
		try {
			System.out.println(Thread.currentThread().getName() + " 到了 在等待其他人都到了开始起跑 ");
			/*if (Thread.currentThread().getName().equals("Thread-2")) {
				System.out.println(" thread-2 进来了" );
				Thread.sleep(5000);
				Integer.parseInt("a");
			}*/
			if (Thread.currentThread().getName().equals("Thread-2")) {
				System.out.println(" thread-2 进来了" );
				Thread.sleep(5000);
				Thread.currentThread().interrupt();
			}
			cbRef.await();
			System.out.println(" 都到了，开始跑！");
			System.out.println(Thread.currentThread().getName() + " 到达终点，并结束第 " + count + "赛段 ");
		} catch (InterruptedException e) {
			System.out.println(" 进入 InterruptedException e " + cbRef.isBroken());
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			System.out.println(" 进入 BrokenBarrierException e " + cbRef.isBroken());
			e.printStackTrace();
		}
	}
	
	public void testA() {
		//比赛1个赛段
		for (int i = 0; i < 1; i++) {
			beginRun( i+ 1);
		}
	}
}
